//
//  CarOrder.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/10.
//

import Combine
import CoreLocation
import Foundation

class CarOrder: ObservableObject {
   static let shared = CarOrder()
    
    
   var orderId: String = ""
   var driverId: String = ""
   var passengerId: String = ""
   var mydistance: Int = 0

   var willChange = PassthroughSubject<Void, Never>()

    
    var laosPoint: LaosPoint = LaosPoint(chepai: "", course: "", latitude: 0, leftTime: 0, longitude: 0, mydistance: 0, mytime: 0, name: "", openid: "", pointStatus: 0, time: 0, traceCode: "", waitEnd: 0, waitStart: 0, waitTime: 0, speed: 0,price: 0)
    
   @Published var messages: [Message] = [] {
      willSet {
         print("chat message changed.")
         willChange.send()
         save()
      }
   }

   @Published var messageCount: Int = 0

   @Published var distance: String = "" // 接到乘客前，司机与乘客的距离
   @Published var leftTime: String = ""

   var startTime: Int64 = 0

   var carNo: String = ""
   var driverPhone: String = "" // 司机老挝电话

   var driverWechat: String = "" // 司机微信

    var headavitor: String = "" // 司机头像
    
    var fanwei: Int  = 3
    
   @Published var carDirection: Double = 0 // 车辆行驶方向

   @Published var carPosition: CLLocationCoordinate2D?
   @Published var passengerPosition: CLLocationCoordinate2D?

   @Published var selectPosType : Int = 0  // 0 startPos ; 1 endPos

   @Published var selectPos: CLLocationCoordinate2D? {
      willSet {
         print("[Map] selectPos changed.")
         willChange.send()
      }
   }

   @Published var startPos: CLLocationCoordinate2D? {
      willSet {
         print("[Map] startPos changed.")
         willChange.send()
      }
   }

   @Published var endPos: CLLocationCoordinate2D? {
      willSet {
         print("[Map] endPos changed.")
         willChange.send()
      }
   }

   @Published var startLabel: String = "" {
      willSet {
         print("[Map] startLabel changed.")
         willChange.send()
      }
   }
   @Published var endLabel: String = "" {
      willSet {
         print("[Map] endLabel changed.")
         willChange.send()
      }
   }

   private init() {
      if let v = UserDefaults.standard.string(forKey: "CarNo") {
         carNo = v
         print("carNo:\(carNo)")
      }

      if let v = UserDefaults.standard.string(forKey: "DriverPhone") {
         driverPhone = v
      }

      if let v = UserDefaults.standard.string(forKey: "DriverWechat") {
         driverWechat = v
      }

      if let v = UserDefaults.standard.string(forKey: "DriverId") {
         driverId = v
      }

      if let v = UserDefaults.standard.string(forKey: "OrderId") {
         orderId = v
      }
       if let v = UserDefaults.standard.string(forKey: "startTime") {
           startTime = Int64(v)!
       }
       if let v = UserDefaults.standard.string(forKey: "driverPhone") {
           driverPhone = v
       }
       if let v = UserDefaults.standard.string(forKey: "driverWechat") {
           driverWechat = v
       }
       if let v = UserDefaults.standard.string(forKey: "startLabel") {
           startLabel = v
       }
       if let v = UserDefaults.standard.string(forKey: "endLabel") {
           endLabel = v
       }
       if let v = UserDefaults.standard.string(forKey: "mydistance") {
           mydistance = Int(v)!
       }
       if let v = UserDefaults.standard.string(forKey: "headavitor") {
           headavitor = v
       }
       
       // 读取坐标
       if let coordinateDict = UserDefaults.standard.dictionary(forKey: "startPos") as? [String: Double],
          let latitude = coordinateDict["latitude"],
          let longitude = coordinateDict["longitude"] {
           let savedCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
           startPos = savedCoordinate
       }
       // 读取坐标
       if let coordinateDict = UserDefaults.standard.dictionary(forKey: "endPos") as? [String: Double],
          let latitude = coordinateDict["latitude"],
          let longitude = coordinateDict["longitude"] {
           let savedCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
           endPos = savedCoordinate
       }
       
      if let v = UserDefaults.standard.object(forKey: "Messages") as? Data, let msgs = try? JSONDecoder().decode([Message].self, from: v) {
         print("saved chat messages:\(msgs)")
         messages = msgs
      }
   }

   func isExistMessage(num: Int, type: Message.MessageType, message: String) -> Bool {
      if CarOrder.shared.messages.count == 0 {
         return false
      }
      let lastItems = Array(CarOrder.shared.messages.suffix(num))
      if lastItems.count == 0 {
         return false
      }
      switch type {
         case .text:
            return lastItems.contains(where: { $0.text == message && $0.type == .text })
         case .image:
            return lastItems.contains(where: { $0.url == message && $0.type == .image })
         case .voice:
            return lastItems.contains(where: { $0.url == message && $0.type == .voice })
         case .video:
            return lastItems.contains(where: { $0.url == message && $0.type == .video })
      }
   }

    func clear() {
        carNo = ""
        driverPhone = ""
        driverWechat = ""
        orderId = ""
        driverId = ""
        startPos = nil
        endPos = nil
        endLabel = ""
        headavitor = ""
        messages.removeAll()
        save()
    }

   func save() {
      UserDefaults.standard.set(orderId, forKey: "OrderId")
      UserDefaults.standard.set(driverWechat, forKey: "DriverWechat")
      UserDefaults.standard.set(driverPhone, forKey: "DriverPhone")
      UserDefaults.standard.set(carNo, forKey: "CarNo")
      UserDefaults.standard.set(driverId, forKey: "DriverId")
      UserDefaults.standard.set(startTime, forKey: "startTime")
       UserDefaults.standard.set(driverPhone, forKey: "driverPhone")
       UserDefaults.standard.set(driverWechat, forKey: "driverWechat")
       UserDefaults.standard.set(startLabel, forKey: "startLabel")
       UserDefaults.standard.set(endLabel, forKey: "endLabel")
       UserDefaults.standard.set(headavitor, forKey: "headavitor")
      if let encoded = try? JSONEncoder().encode(messages) {
         UserDefaults.standard.set(encoded, forKey: "Messages")
      }
       if let pos = self.startPos{
           let coordinateDict: [String: Double] = [
            "latitude": pos.latitude,
               "longitude": pos.longitude
           ]
           UserDefaults.standard.set(coordinateDict, forKey: "startPos")
       }
       
       if let pos = self.endPos{
           let coordinateDict: [String: Double] = [
            "latitude": pos.latitude,
               "longitude": pos.longitude
           ]
           UserDefaults.standard.set(coordinateDict, forKey: "endPos")
       }
       
      UserDefaults.standard.synchronize()
   }
    
    
    // 保存订单信息
    func save(info: LaosPoint) {
      let encoder = JSONEncoder()
      if let data = try? encoder.encode(info) {
        UserDefaults.standard.set(String(decoding: data, as: UTF8.self), forKey: "LaosPoint")
        UserDefaults.standard.synchronize()
      } else {
        print("Save LaosPoint info failure.")
      }
    }
    
    // 读取或者初始化
    func read() -> LaosPoint? {
      let data = UserDefaults.standard.string(forKey: "LaosPoint")
      if let d = data {
        let coder = JSONDecoder()
        let p = try? coder.decode(LaosPoint.self,from:Data(d.utf8))
        return p!
      }
        return LaosPoint(chepai: "", course: "", latitude: 0, leftTime: 0, longitude: 0, mydistance: 0, mytime: 0, name: "", openid: "", pointStatus: 0, time: 0, traceCode: "", waitEnd: 0, waitStart: 0, waitTime: 0, speed: 0,price: 0)
    }
}
